/*
 * @version: vue3
 * @Author: lxs
 * @Date: 2022-04-30 19:36:02
 * @LastEditors: sueRimn
 * @LastEditTime: 2022-05-01 12:55:53
 */
import { login, LoginParm } from "@/api/user/user";
import { ElMessage } from "element-plus";
import { setToken, setUserId, setExpireTime } from "@/utils/auth";
export type UserState = {
  token: string;
  userId: string;
};

export const state: UserState = {
  token: "",
  userId: "",
};
export const mutations = {
  setToken(state: UserState, token: string) {
    state.token = token;
  },
  setUserId(state: UserState, userId: string) {
    state.userId = userId;
  },
};
export const actions = {
  Login: async ({ commit }: any, loginParm: any) => {
    return new Promise(async(resolve,reject)=>{
      try {
        let res: any = await login(loginParm);
        console.log(res);
        if (res.code == 200) {
          //设置到vuex中
          commit("setToken", res.token);
          commit("setUserId", res.id);
          //存储到sessionStorage
          setToken(res.token);
          setUserId(res.id);
          setExpireTime(res.expireTime);
          resolve(res)
        }else{
          reject(new Error('用户名或密码错误'))
        }
      } catch (error: any) {
        console.log(error, "log");
        reject(error)
      }
    })    
  },
};
export const getters = {};
export default {
  namespace: true,
  state,
  mutations,
  actions,
  getters,
};
